package com.example.demo.config;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.web.SecurityFilterChain;


@EnableWebSecurity

@Configuration

public class SecurityConfig {


    @Autowired

    private DatabaseUserDetailsService databaseUserDetailsService;


    /*@Bean
    public PasswordEncoder passwordEncoder() {
        // 返回 DelegatingPasswordEncoder，它能处理 {noop} 前缀的密码
        return org.springframework.security.crypto.factory.PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
*/
    @Bean

    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder(16);

    }
    @Bean

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http

                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/user/**").permitAll()  // 添加这行
                        .anyRequest().authenticated()

                )

                .userDetailsService(databaseUserDetailsService)

                .formLogin(form -> form

                        .loginPage("/login")

                        .permitAll()

                );

        return http.build();

    }


}